package com.link.base.tencent.corpwx.accounttag.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.accounttag.dao.mybatis.mapper.AccountTagGroupMapper;
import com.link.base.tencent.corpwx.accounttag.dao.mybatis.mapper.AccountTagItemMapper;
import com.link.base.tencent.corpwx.accounttag.model.AccountTagGroup;
import com.link.base.tencent.corpwx.accounttag.model.AccountTagItem;
import com.link.base.tencent.corpwx.accounttag.util.AccountTagUtil;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户标签 - 标签组
 *
 * @author 欧阳振强
 * @date 2020-01-02 14:56:55.0
 */
@Service
public class AccountTagGroupServiceImpl extends BasicServiceImpl<AccountTagGroup> implements AccountTagGroupService {

    @Resource
    private AccountTagGroupMapper accountTagGroupMapper;
    @Resource
    private AccountTagItemMapper accountTagItemMapper;
    @Resource
    private AccountTagItemService accountTagItemService;
    @Resource
    private AgentService agentService;
    @Resource
    private KeyGenerateService keyGenerateService;
    
    @Override
    public BasicMapper<AccountTagGroup> getBasicMapper() {
        return accountTagGroupMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncAllCorpTagFromWx() throws Exception {
        // 获取企业微信所有标签
        JSONObject tagData = AccountTagUtil.getCorpTagList(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID));
        JSONArray tagGroupArray = tagData.getJSONArray("tag_group");
        for (int i = 0; i < tagGroupArray.size(); i++) {
            JSONObject tagGroupObj = tagGroupArray.getJSONObject(i);
            // 判断tag group是否存在
            AccountTagGroup accountTagGroupParam = new AccountTagGroup();
            accountTagGroupParam.setTagGroupId(tagGroupObj.getString("group_id"));
            AccountTagGroup accountTagGroup = accountTagGroupMapper.getTagGroupById(accountTagGroupParam);
            if (accountTagGroup == null) {
                // 不存在，则新建标签组
                accountTagGroupParam = AccountTagUtil.getTagGroupFromJSON(tagGroupObj);
                Long tagGroupCrmId = keyGenerateService.keyGenerate();
                accountTagGroupParam.setId(tagGroupCrmId);
                accountTagGroupMapper.insert(accountTagGroupParam);
                // 开始新建标签
                JSONArray tagArray = tagGroupObj.getJSONArray("tag");
                if (tagArray != null) {
                    for (int j = 0; j < tagArray.size(); j++) {
                        JSONObject tagObj = tagArray.getJSONObject(j);
                        AccountTagItem accountTagItemParam = AccountTagUtil.getTagItemFromJSON(tagObj);
                        accountTagItemParam.setHeadId(tagGroupCrmId);
                        accountTagItemParam.setId(keyGenerateService.keyGenerate());
                        accountTagItemMapper.insert(accountTagItemParam);
                    }
                }
            } else {
                // 存在标签组，则跳过处理标签组，直接处理标签
                Long tagGroupCrmId = accountTagGroup.getId();
                JSONArray tagArray = tagGroupObj.getJSONArray("tag");
                if (tagArray != null) {
                    for (int j = 0; j < tagArray.size(); j++) {
                        JSONObject tagObj = tagArray.getJSONObject(j);
                        // 判断tag是否存在
                        AccountTagItem accountTagItemParam = new AccountTagItem();
                        accountTagItemParam.setTagId(tagObj.getString("id"));
                        AccountTagItem accountTagItem = accountTagItemMapper.getTagItemById(accountTagItemParam);
                        if (accountTagItem == null) {
                            // 不存在则新建标签
                            accountTagItemParam = AccountTagUtil.getTagItemFromJSON(tagObj);
                            accountTagItemParam.setHeadId(tagGroupCrmId);
                            accountTagItemParam.setId(keyGenerateService.keyGenerate());
                            accountTagItemMapper.insert(accountTagItemParam);
                        } else {
                            // 标签已存在，暂时做不做操作
                        }
                    }
                }
            }
        }
    }

    @Override
    public void delTagGroupById(AccountTagGroup accountTagGroup) throws Exception {
        String tagGroupId = accountTagGroup.getTagGroupId();
        if (StringUtils.isNotBlank(tagGroupId)) {
            // 存在标签组Id，即已经同步到企业微信，此时需要一并删除企业微信端的标签
            // 构造标签组列表对象
            List<String> tagGroupList = new ArrayList<>();
            tagGroupList.add(tagGroupId);
            // 获取标签组下的标签一并删除
            List<String> tagList = new ArrayList<>();
            List<AccountTagItem> accountTagItemList = accountTagItemMapper.getTagItemListByGroupId(accountTagGroup);
            for (AccountTagItem item: accountTagItemList) {
                // 标签组下可能存在尚未同步到企业微信的标签，跳过处理
                if (StringUtils.isNotBlank(item.getTagId())) {
                    tagList.add(item.getTagId());
                }
            }
            AccountTagUtil.delCorpTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID), tagGroupList, tagList);
        }
        // 删除CRM侧标签组和标签
        accountTagGroupMapper.deleteById(accountTagGroup);
        accountTagItemMapper.delTagItemListByGroupId(accountTagGroup);
    }

    @Override
    public void syncTagGroupToWx(AccountTagGroup accountTagGroup) throws Exception {
        // 获取标签组下的所有标签
        List<AccountTagItem> accountTagItemList = accountTagItemMapper.getTagItemListByGroupId(accountTagGroup);
        if (accountTagItemList == null || accountTagItemList.size() <= 0) {
            throw new BasicServiceException("请为该标签组维护标签！");
        }
        String tagGroupId = accountTagGroup.getTagGroupId();
        if (StringUtils.isBlank(tagGroupId)) {
            // 标签组Id为空，该标签组尚未同步到企业微信，则一并打包同步
            // 新增标签组和标签
            JSONObject resultObj = AccountTagUtil.addCorpTagGroup(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID),
                accountTagGroup.getTagGroupName(), accountTagGroup.getTagGroupOrder(), accountTagItemList);
            resultObj = resultObj.getJSONObject("tag_group");
            // 回写标签组信息
            accountTagGroup.setTagGroupId(resultObj.getString("group_id"));
            accountTagGroup.setCreateTime(resultObj.getString("create_time"));
            accountTagGroup.setTagGroupOrder(resultObj.getString("order"));
            accountTagGroupMapper.update(accountTagGroup);
            // 比对标签名称，回写标签信息到数据库
            accountTagItemService.setTagItemByJSON(resultObj.getJSONArray("tag"), accountTagItemList);
        } else {
            // 标签组Id不为空，更新标签组
            AccountTagUtil.editCorpTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID),
                tagGroupId, accountTagGroup.getTagGroupName(), accountTagGroup.getTagGroupOrder());
            // 需要新建的标签对象列表
            List<AccountTagItem> addAccountTagItemList = new ArrayList<>();
            for (AccountTagItem item: accountTagItemList) {
                if (StringUtils.isBlank(item.getTagId())) {
                    addAccountTagItemList.add(item);
                } else {
                    // 标签Id不为空，则直接更新
                    AccountTagUtil.editCorpTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID),
                        item.getTagId(), item.getTagName(), item.getTagOrder());
                }
            }
            // 新建标签
            if (addAccountTagItemList.size() > 0) {
                JSONObject resultObj = AccountTagUtil.addCorpTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID),
                    tagGroupId, addAccountTagItemList);
                // 比对标签名称，回写标签信息到数据库
                accountTagItemService.setTagItemByJSON(resultObj.getJSONObject("tag_group").getJSONArray("tag"), accountTagItemList);
            }
        }
    }
}